package handlers

import (
	"github.com/gin-gonic/gin"
	"post-mgr/cache"
	"time"

	"post-mgr/models"
	"post-mgr/pkg"
)

func Login(c *gin.Context) {
	var err error
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"message": "字段不可为空",
			"code":    500,
		})
		return
	}

	//判断密码错误三次
	redis_login_key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"message": "密码错误3次",
			"code":    500,
		})
		return
	}
	var user models.User
	err = models.DB.Where("username = ?", username).Debug().First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"message": "用户查询失败",
			"code":    500,
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"message": "用户不存在",
			"code":    500,
		})
		return
	}
	
	if user.Password != pkg.MD5string(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"message": "密码错误3次，封禁2个小时",
				"code":    500,
			})
			return
		}
		c.JSON(200, gin.H{
			"message": "密码错误",
			"code":    500,
		})
		return
	}

	c.JSON(200, gin.H{
		"message": "登录成功",
		"code":    200,
		"data":    user,
	})
	return
}
